<template>
  <el-container>
    <div style="padding: 10px;padding-bottom: 0">
      <div class="report_header" ref="headerHeight">
        <div style="display: flex;align-items: center">
          <div class="report_header_left"></div>
          <div style="width: 800px;display: flex;align-items: center;">
            <div class="report_header_date">
              <el-date-picker
                v-model="query.date"
                value-format="yyyy-MM-dd"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="queryClick"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
            <div class="report_header_query">
              <el-select  v-model="sysMchName"   placeholder="请选择商户" filterable
                          value-key="id" :filter-method="querySysmch" clearable @change="changeSysMch">
                <el-option style="width:300px" v-for="item in mchIdOptions" :key="item.id" :label="item.name" :value="item">
                </el-option>
                <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                  <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                  <div class="elOption" @click="sysClick">搜索商户</div>
                </div>
                <div style="height: 40px"></div>
              </el-select>
            </div>
          </div>
          <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">

            <el-button style="margin-left: 10px;margin-top: 7px;height: 100%" size="small" type="primary"
                       @click="queryClick">查询
            </el-button>
            <ExportList2Excel ref="exportList2Excel" style="margin-left: 10px;margin-top: 7px;height: 32px;padding: 9px 15px" @handleExport="handleExport" v-permission="['billsSummary.export']" />
          </div>
        </div>
        <div style="width: 800px;display: flex;align-items: center;" v-show="queryType == true">
          <!--          这是放隐藏条件的容器-->
        </div>
      </div>
    </div>
    <div class="pd10">
<!--      暂不开启总和行-->
<!--      <el-table :data="orderForm" :height="curHeight" style="width: 100%;" row-key="id" border stripe show-summary-->
<!--                :summary-method="summaryMethod" @sort-change="sortChange" sortable="custom">-->
        <el-table :data="orderForm" :height="curHeight" style="width: 100%;" row-key="id" border stripe @sort-change="sortChange">
        <el-table-column :label="item.label" :prop="item.prop" align="center"
                         v-for="(item,index) in labelAndProp" :key="index" sortable="custom"/>
      </el-table>
    </div>
    <el-dialog
      title="双击选择商户"
      :visible.sync="mchTableVisible"
      width="650px"
      v-el-drag-dialog
      append-to-body
      :before-close="mchTableClose">
      <div style="position: relative;">
        <enterprise @mchDouble="mchDouble"></enterprise>
      </div>
    </el-dialog>
    <el-footer class="el-footerBox" style="margin-bottom: auto">
      <pagination :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                  @pagination="pagination"></pagination>
    </el-footer>
  </el-container>
</template>

<script>
  import Pagination from "@/components/Pagination/index";
  import enterprise from "@/components/Enterprise/index";
  import permission from "@/directive/permission";
  import elDragDialog from "@/directive/el-drag-dialog";
  import {mapGetters} from "vuex";
  import {EventBus} from "@/api/eventBus";
  import utils from "@/utils/utils";
  import {list as mchList} from "@/api/enterprise";
  import {shopSaleDetail} from "@/api/reportOrder";
  import {dateFormatter} from "@/filters";
  import ExportList2Excel from "@/components/ExportList2Excel/index";

  export default {
    name: 'billsSummary-list',
    components: {ExportList2Excel, Pagination, enterprise},
    directives: {elDragDialog, permission},
    activated() {
      this.payLoads = new Date().getTime()
    },
    data() {
      return {
        sortField: 'date',
        direction:'asc',
        orderForm: [],
        labelAndProp: [
          // {
          //   label: "序号",
          //   prop: "balance"
          // },
          {
            label: "日期",
            prop: "date"
          }, {
            label: "商家名称",
            prop: "name"
          }, {
            label: "订单量",
            prop: "orderNum"
          }, {
            label: "商品合计金额",
            prop: "totalSubPrice"
          }, {
            label: "平台红包抵扣金额",
            prop: "totalCouponAmount"
          },
          // {
          //   label: "新人红包抵扣金额",
          //   prop: "orderDate"
          // },
          {
            label: "平台运费",
            prop: "totalRiderFee"
          },{
            label: "包装费",
            prop: "totalFreight"
          }, {
            label: "用户实付金额",
            prop: "totalAmountPaid"
          }
          // , {
          //   label: "当日商品总额排名",
          //   prop: "status"
          // },
        ],
        mchTableVisible: false,
        pageNum: 1,
        pageSize: 20,
        total: 0,
        curHeight: null,
        sysMchName: '',
        enterpriseId: '',
        queryType: true,
        mchIdOptions: [],
        orderStatus: 0, // 订单状态
        query: {
          date: [],
          orderSn: '',

          memberId: '',
          phone: '',
          productId: ''
        },
        keyword: {
          date: [],
          orderSn: '',
          memberId: '',
          phone: '',
          productId: ''
        },
        pickerOptions: {//时间快捷选择
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              picker.$emit('pick', [start, end])
            }
          },{
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              end.setTime(end.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '本月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setDate(1)
              picker.$emit('pick', [start, end])
            }
          },{
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        }
      }
    },

    computed: {
      ...mapGetters([
        'mchId'
      ])
    },
    created() {
      var _this = this
      this.loadMch('')
      this.loadOrder()
      EventBus.$on('order-view', res => { // 监听订单删除
        // 更新列表数组
        for (var i = 0; i < _this.orderForm.length; i++) {
          if (_this.orderForm[i].id == res.id) {
            _this.$set(this.orderForm, i, res)
          }
        }
      })
    },
    mounted() {
      this.comeIn()
      // this.beforeMount()
    },
    beforeMount() {
      var _this = this
      window.onresize = () => {
        return (() => {
          var h = document.documentElement.clientHeight || document.body.clientHeight
          if (!_this.queryType) {
            _this.curHeight = h - 311//减去页面上固定高度height
          } else {
            _this.curHeight = h - 224//减去页面上固定高度height
          }
        })()
      }
    },
    methods: {
      mchTableClose(){
        this.mchTableVisible=false
      },
      sysClick(){
        this.mchTableVisible=true
      },
      mchDouble(data){
        this.sysMchName=data.name
        this.enterpriseId=data.enterpriseId
        this.mchTableVisible=false
        this.loadOrder()
      },
      changeSysMch(data){
        if (!utils.isNull(data)){
          this.sysMchName=data.name
          this.enterpriseId=data.id

        }else{
          this.sysMchName=''
          this.enterpriseId=''
        }

      },
      querySysmch(query){
        this.loadMch(query)
      },
      loadMch(query){
        mchList({
          name:query
        }).then(res=>{
          this.mchIdOptions=res.data.data
        })
      },

      setCurHeight(){
        var _this = this
        var h = document.documentElement.clientHeight || document.body.clientHeight
        if (_this.queryType === false) {
          _this.curHeight = h - 311//减去页面上固定高度height
        } else {
          _this.curHeight = h - 224//减去页面上固定高度height
        }
      },
      comeIn() {
        setTimeout(()=>{
          this.setCurHeight()
        },1000)
        var h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 225//减去页面上固定高度height
      },
      loadOrder(pageNum,pageSize) {
        //TODO 也需要获取到统计数据
        var _this = this
        let params = new URLSearchParams()
        params.append('pageNum', pageNum||_this.pageNum)
        params.append('pageSize', pageSize||_this.pageSize)
        params.append('status', _this.orderStatus)
        params.append('sortField', _this.sortField||'')
        params.append('direction', _this.direction||'')
        if(!utils.isNull(_this.enterpriseId)){
          params.append('enterpriseId',_this.enterpriseId)
        }
        if(this.keyword.date != null && this.keyword.date.length != 0){
          params.append('startDate', this.keyword.date[0])
          params.append('endDate', this.keyword.date[1])
        }else{
          params.append('startDate', '2021-01-01')
          params.append('endDate', dateFormatter(new Date().getTime()))
        }
        shopSaleDetail(params).then(res => {
          res.data.data=res.data.data.map(e=>{
            return{
              ...e,
              date:dateFormatter(e.date),
              totalAmountPaid: e.totalAmountPaid.toFixed(2),
              totalCouponAmount: e.totalCouponAmount.toFixed(2),
              totalFreight: e.totalFreight.toFixed(2),
              totalRiderFee: e.totalRiderFee.toFixed(2),
              totalSubPrice: e.totalSubPrice.toFixed(2),
            }
          })
          if(pageNum!==undefined&&pageSize!==undefined){
            _this.downLoad(res.data.data)
            return
          }
          _this.total = res.data.total
          _this.orderForm = res.data.data
        }).catch(error => {
          console.log('error!!')
        })
      },

      queryClick() {
        this.keyword = this.query
        this.pageNum = 1
        this.loadOrder()
      },
      downLoad(outputData){
        let columnCount = this.labelAndProp.length
        let rowCount = outputData.length
        let filename = this.query.date.length?`${this.query.date[0]}~${this.query.date[1]}餐巴清单汇总`:'餐巴清单汇总'
        let multiHeader = [[filename, ...new Array(columnCount - 1).fill('')]];
        // let merges = [`A1:${String.fromCharCode(columnCount + 64)}1`,`A${rowCount+3}:B${rowCount+3}`]; //暂不处理超过24列的情况
        let merges = [`A1:${String.fromCharCode(columnCount + 64)}1`]; //暂不处理超过24列的情况
        let tHeader = this.labelAndProp.map(e => e.label);
        let filterVal = this.labelAndProp.map(e => e.prop);
        let countRow = outputData.reduce((acc,cur)=>{
          filterVal.forEach(e=>{
              let curVal = Number(cur[e]||0)*100
              if(curVal === curVal){
                acc[e] = ((Number(acc[e]||0)*100 + curVal)/100).toFixed(2)
              }else{
                acc[e] = ''
              }
          })
          return acc
        },{})
        countRow[filterVal[0]] = "合计"
        let list = outputData.concat(countRow);
        this.$refs.exportList2Excel.handleDownload(
          {
            multiHeader: multiHeader,
            merges: merges,
            tHeader: tHeader,
            filterVal: filterVal,
            list: list,
            filename: filename
          }
        )
      },
      handleExport() {
        //TODO 最长导出时间间隔？
        // if(!this.query.date.length){
        //   this.$message({
        //     message: '请选择日期后再导出',
        //     type: 'warning'
        //   });
        //   return
        // }
        //TODO 再次全量查询所需下载的数据
        this.loadOrder(1,100000)

      },
      summaryMethod({columns,data }){
        return ["合计","",...new Array(columns.length-2).fill(1)]
      },
      sortChange(column) {
        this.sortField = column.prop;
        if (column.order === 'ascending') {
          this.direction = 'asc'
        } else {
          this.direction = 'desc'
        }
        this.loadOrder()
      },
      pagination({page, limit}) {
        this.pageNum = page
        this.pageSize = limit
        this.loadOrder()
      }
    }
  }
</script>

<style scoped>
  .details_card {
    overflow: auto;
    padding-left: 20px;
    padding-right: 20px;
    box-sizing: border-box;
    border: 1px solid #f2f2f2;
    border-radius: 4px;
  }

  .elOption {
    background-color: #909399;
    color: white;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 40px
  }

  .details_card:hover {
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
  }

  .el-input__inner {
    width: 100% !important;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/ .el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
    flex-direction: column;
  }
  /deep/.el-dialog__header{
    border-bottom: 1px solid rgba(0,0,0,0.1);
  }
  .report_header_left {
    width: 5px;
    height: 46px;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }

  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
</style>
